package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.http.ApiService
import com.frxuexi.lib_base.http.ShopApiService
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class MviViewModel @Inject constructor(val apiService: ApiService):ViewModel(){

    //作用：发送和接收意图
    val channel= Channel<MviIntent>()

    private var _state= MutableStateFlow<MviState>(MviState.onLoading)
    val state:StateFlow<MviState>
        get() = _state

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                when(it){
                    is MviIntent.getShops->{
                        getShops(it.type,it.page)
                    }
                    is MviIntent.getNews->{
                        getNews()
                    }
                }
            }
        }
    }

    fun getNews(){
        viewModelScope.launch {
            apiService.getNews().flowOn(Dispatchers.IO)
                .catch {
                    Log.i("lr",it.message.toString())
                }.collect{
                    if(it.code==200){
                        _state.value=MviState.onSuccess(it.data)
                    }else{
                        _state.value=MviState.onError(it.message)
                    }
                }
        }
    }

    fun getShops(type:Int,page:Int){
        viewModelScope.launch {
            /*apiService.getShops(type, page).flowOn(Dispatchers.IO)
                .catch {
                    Log.i("lr",it.message.toString())
                }.collect{
                    if(it.code==200){
                        _state.value=MviState.onSuccess(it.data)
                    }else{
                        _state.value=MviState.onError(it.message)
                    }
                }*/
        }
    }

}